package org.brakepedal.server.support.controller.responseBodyAdvice;

import org.brakepedal.server.support.controller.annotation.DisableResponseBodyConverter;
import org.brakepedal.server.support.http.AbsResponseBody;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.ResponseEntity;

import java.util.Objects;

/**
 * Date: 2023/2/13 14:48
*/
public class AdviceSupportUtil {

    public static boolean isInstanceof(Class<?> clazz, @NotNull MethodParameter returnType, @NotNull Class converterType) {
        if(returnType.hasMethodAnnotation(DisableResponseBodyConverter.class)) {
            return false;
        }
        Class<?> type = Objects.requireNonNull(returnType.getMethod()).getReturnType();
        try {
            return clazz.isAssignableFrom(type);
        } catch (RuntimeException ignored) {
            return false;
        }
    }

    public static boolean isResponseBody(MethodParameter returnType, @NotNull Class converterType){
        return isInstanceof(AbsResponseBody.class,returnType,converterType);
    }

    public static boolean isPlainBody(@NotNull MethodParameter returnType, @NotNull Class converterType) {
        return !returnType.hasMethodAnnotation(DisableResponseBodyConverter.class) && !(
                        isResponseBody(returnType, converterType)
                        || isInstanceof(ResponseEntity.class, returnType,converterType)
                );
    }

}
